package com.golddaymicromall.activity.setting.personal.address;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AddressInfo;
import com.golddaymicromall.util.IsNetUtils;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.view.DragDelItem;
import com.golddaymicromall.view.DragDelListView;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;


public class AddressActivity extends BaseActivity implements View.OnClickListener {
    private DragDelListView mlv;
    private ArrayList<String> list1 = new ArrayList<String>();
    private List<AddressInfo> list;
    private String customerid;
    private AppAdapter adapter;
    private Button mnewadd_btn;
    private int posion1;
    private ProgressBar progress;
    private LinearLayout mmyadress_back;
    private MyApplication Application;
    private String Customerno;
    private IsNetUtils isnet;
    int width;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;     // 屏幕宽度（像素）

        setContentView(R.layout.activity_address);
        isnet = new IsNetUtils(AddressActivity.this);
        customerid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        initView();


    }

    @Override
    protected void onResume() {
        super.onResume();
        attemptgetAddressinfo();
    }

    public void initView() {
        progress = (ProgressBar) findViewById(R.id.progress);
        mnewadd_btn = (Button) findViewById(R.id.newadd_btn);
        mnewadd_btn.setOnClickListener(this);
        mlv = (DragDelListView) findViewById(R.id.addressLv);
        mmyadress_back = (LinearLayout) findViewById(R.id.activity_myadress_back);
        mmyadress_back.setOnClickListener(this);
    }


    public void attemptdeleAddress(String id, int posion) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.deleteaddress.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", id);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (Integer.parseInt(s) == 1) {
                        Toast.makeText(AddressActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        list.remove(posion);
                        adapter.notifyDataSetChanged();
                        MyApplication.getInstance().attemptRiZhi(Customerno, "地址删除");
                    } else {
                        Toast.makeText(AddressActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }


    public void attemptgetAddressinfo() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerId", customerid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list = JSON.parseArray(s, AddressInfo.class);
                            adapter = new AppAdapter();
                            mlv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.newadd_btn:
                Intent intent = new Intent(this, NewAddShouHuoActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_myadress_back:
                finish();
                break;
        }
    }


    class AppAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final int loc = position;
            ViewHolder holder = null;
            View menuView = null;
            if (convertView == null) {


                convertView = View.inflate(getApplicationContext(),
                        R.layout.swipecontent, null);

                menuView = View.inflate(getApplicationContext(),
                        R.layout.swipemenu, null);
                convertView = new DragDelItem(convertView, menuView);
                holder = new ViewHolder(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mname_address.setText(list.get(position).getReceivername());
            holder.mneirongq.setText(list.get(position).getCountryname() + list.get(position).getProvincename() + list.get(position).getCityname() + list.get(position).getAreaname() + list.get(position).getStreet());
            if (list.get(position).getAddress_default().equals("1")) {
                holder.swipecontent_def.setText("【默认】");
            } else {
                holder.swipecontent_def.setText("");
            }
            holder.mtelephonenumber.setText(list.get(position).getPhone());
            holder.tv_updete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (!isnet.IsNet()) {
                        Toast.makeText(AddressActivity.this, "网络漫游中请查看是否有网", Toast.LENGTH_SHORT).show();

                    } else {
                        Intent intent = new Intent(getApplicationContext(), AddressUpDateActivity.class);
                        intent.putExtra("id", list.get(position).getId());
                        intent.putExtra("CustomerId", list.get(position).getCustomerId());
                        intent.putExtra("Province", list.get(position).getProvince());
                        intent.putExtra("city", list.get(position).getCity());
                        intent.putExtra("are", list.get(position).getArea());
                        startActivity(intent);
                    }

                }
            });
            holder.tv_del.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    attemptdeleAddress(list.get(position).getId(), position);
                    notifyDataSetChanged();
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView mname_address;
            TextView mneirongq;
            TextView mtelephonenumber;
            TextView tv_updete, tv_del;
            TextView swipecontent_def;
            RelativeLayout Rv;
            LinearLayout up;

            public ViewHolder(View view) {
                Rv = (RelativeLayout) view.findViewById(R.id.Rv);
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) Rv.getLayoutParams();
                linearParams.width = width;
                mname_address = (TextView) view.findViewById(R.id.swipecontent_name_address);
                mneirongq = (TextView) view.findViewById(R.id.swipecontent_address);
                mtelephonenumber = (TextView) view.findViewById(R.id.swipecontent_telephonenumber);
                tv_updete = (TextView) view.findViewById(R.id.tv_updete);
                tv_del = (TextView) view.findViewById(R.id.tv_del);
                swipecontent_def = (TextView) view.findViewById(R.id.swipecontent_def);
                view.setTag(this);
            }
        }
    }


}
